//
//  ZHOAuthController.swift
//  ZHWeibo
//
//  Created by user on 15/12/7.
//  Copyright © 2015年 heima. All rights reserved.
//

import UIKit
import SVProgressHUD

let fromOauthToWelcome = "fromOauthToWelcome"


class ZHOAuthController: UIViewController, UIWebViewDelegate {
    let WB_APPKEY = "4172081718"
    let WB_APP_SECRET = "6ff9179b059b49b53e512e4706235951"
    let WB_REDIRECT_URI = "http://www.sina.com.cn"
    //懒加载webView
    /// 为什么这些VIEW不用指定frame
    lazy var webview:UIWebView = {
        let tempView = UIWebView()
        tempView.delegate = self
        return tempView
    }()
    
    override func loadView() {
        view = webview
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //初始化控件
        setupUI()
        /// 定义url-------?????????WB_APPKEY为什么不能使用static去修饰
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APPKEY)&redirect_uri=\(WB_REDIRECT_URI)"
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        //加载页面
        webview.loadRequest(request)
    }
    
    private func setupUI(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFill")
        navigationItem.title = "微博登录"
    }
    //webViewdelegate的代理方法---webView将要去加载某个请求的时候,会调用这个方法,决定是否取加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //如果是回调的页面,那么就拦截code,然后利用code去获取token
        
        //如果获取不到url,那就任其加载
        guard let url = request.URL?.absoluteString else{
            return true
        }
        //如果开头不是回调页,任其加载
        if !url.hasPrefix(WB_REDIRECT_URI){
            return true
        }
        //判断是否返回了code
        if request.URL!.query!.hasPrefix("code="){
            let code = request.URL!.query?.substringFromIndex("aaaaa".endIndex)
            ZHUserAccountViewModel.shareAccountInstance.getccessToken(code!, complete: { (isSuccess) -> () in
                if !isSuccess {
                    SVProgressHUD.show()
                    return
                }
                //跳转欢迎页面
                printLog("跳转欢迎页面")
                //弹出本控制器
                SVProgressHUD.dismiss()
                self.dismissViewControllerAnimated(true, completion: nil)
                /**
                  * 问题:navcontroller会销毁吗
                */
                //发送通知,切换到登陆控制器
                NSNotificationCenter.defaultCenter().postNotificationName(fromOauthToWelcome, object: nil)
                
                
            })
        }else{
            dismiss()
        }
        return false
    }
    //根据code获取accessToken
        
    //代理方法监听
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //Item点击方法
    @objc private func dismiss() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func autoFill() {
        //利用JS注入技术
        let jsString = "document.getElementById('userId').value='601584870@qq.com';document.getElementById('passwd').value='zhl1242786122'"
//        let jsString = "document.getElementById('userId').value='yohtr35601@163.com';document.getElementById('passwd').value='qw1987'"
        
        
        webview.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    deinit{
        printLog("释放了哈哈哈哈")
    }
    

}
